package org.esisar.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.esisar.controller.album.AlbumController;
import org.esisar.controller.utils.SessionHelper;
import org.esisar.dao.AlbumStatementCreator;
import org.esisar.dao.JDBCDAO;
import org.esisar.dao.PictureOfAlbumStatementCreator;
import org.esisar.dao.PictureStatementCreator;
import org.esisar.exceptions.AlbumsNotAddedException;
import org.esisar.jdbc.JDBCConnector;
import org.esisar.model.Model;
import org.esisar.model.Picture;
import org.esisar.model.PictureOfAlbum;

public class PhotoController extends HttpServlet{

	// location to store file uploaded
	private static final String UPLOAD_DIRECTORY = "upload";

	private JDBCDAO jdbcDao = new JDBCDAO(); //TODO change this class to static

	
	public void doGet(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException{

		if (req.getParameter("fill") != null){
			
			try {
			Long idClient = SessionHelper.getUserId(req);

			
				List<Model> albums = jdbcDao.findAll(new AlbumStatementCreator(), "idClient", idClient+"");
				
				if (albums.size() == 0){
					throw new AlbumsNotAddedException("You have no albums");
				}
				
				req.setAttribute("albums", albums);
				
				RequestDispatcher dispatcher = req.getRequestDispatcher("/Photo/addPhoto.jsp");
				dispatcher.forward(req, res);
				
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (AlbumsNotAddedException e) {
				req.setAttribute("message", e.getMessage());
				req.getRequestDispatcher("User/panel.jsp").forward(req, res);
				e.printStackTrace();
			}
		
		}
		
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException{

		res.setContentType("text/html");
		
		try {
			String clientId = addPhoto(req, res);
			req.getRequestDispatcher("User/panel.jsp").forward(req, res);

		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String addPhoto(HttpServletRequest req, HttpServletResponse res) throws Exception {

		Map<String,String> parameters = writeFile(req, res);

		String url = parameters.get("url");
		String camera = parameters.get("camera");
		String lens = parameters.get("lens");
		String focal = parameters.get("focal");
		String sensitivity = parameters.get("sensitivity");
		String opening = parameters.get("opening");
		String resolution = parameters.get("resolution");
		String obturation = parameters.get("obturation");
		Long idClient = SessionHelper.getUserId(req);

		Picture picture = new Picture(url, camera, lens, focal, sensitivity, opening, resolution, obturation, idClient);

		PictureStatementCreator creator = new PictureStatementCreator();
		
		Connection connection = JDBCConnector.JDBCConnector.connect();
		
		PreparedStatement preparedStatement = creator.addStatement(connection, picture);
		
		preparedStatement.executeUpdate();
		ResultSet rs = preparedStatement.getGeneratedKeys();
		String idPicture = null;
		if (rs != null && rs.next()) {
			idPicture = rs.getString(1);
		}
		
		String idAlbum = parameters.get("idAlbum");
		String title = parameters.get("title");
		String comments = parameters.get("comments");
		long position = 1;
		
		PictureOfAlbum pictureOfAlbum = new PictureOfAlbum(Long.parseLong(idAlbum), Long.parseLong(idPicture),position+"", title, comments);

		jdbcDao.addToDB(new PictureOfAlbumStatementCreator(), pictureOfAlbum);
		
	
		return idClient+"";
	}

	private Map<String, String> writeFile(HttpServletRequest req, HttpServletResponse res)
			throws FileUploadException, IOException, Exception {


		Map<String,String> reqValues = new HashMap<String,String>();


		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = upload.parseRequest(req);

		// Process the uploaded items
		Iterator<FileItem> iter = items.iterator();

		String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

		// creates the directory if it does not exist
		createDir(uploadPath);

		while (iter.hasNext()) {
			handleFileItem(reqValues, iter.next(), uploadPath);
		}
		return reqValues;
	}

	private void createDir(String uploadPath) {
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
	}


	private void handleFileItem(Map<String, String> reqValues, FileItem item, String uploadPath) throws Exception {
		String filePath;

		if(item.isFormField()){
			reqValues.put(item.getFieldName(), item.getString());
		}
		if (!item.isFormField()) {
			String fileName = new File(item.getName()).getName();
			filePath = uploadPath+ File.separator + fileName;
			File storeFile = new File(filePath);
			item.write(storeFile);

			reqValues.put(item.getFieldName(), filePath);
		}
	} 
}

